<template>
  <div class="tp">
    <Header />
    <Content>
      <div class="cp mb-60px">
        <div class="card">
          <div class="c-title"> 基础信息</div>

          <BasicForm @register="registerForm1" class="form">
            <!-- 商品类型 -->
            <template #cateType="{ model, field }">
              <div class="cate-type">
                <div
                  :class="['use', 'cell', model[field] === o.value ? 'active' : 'tacit']"
                  v-for="o in proCategoryType2.filter(
                    (o) => state.behavior === 'add' || o.value === model[field],
                  )"
                  :key="o.value"
                  @click="
                    state.behavior === 'add' && onCateTypeChange({ model, field, value: o.value })
                  "
                  >{{ o.label }}
                </div>
              </div>
            </template>

            <!-- 次卡类型 -->
            <template #cardSubType="{ model, field }">
              <div class="card-sub-type">
                <div
                  :class="['use', 'cell', model[field] === o.value ? 'active' : 'tacit']"
                  v-for="o in getChildren(proCardType, model.cardType) ?? []"
                  :key="o.value"
                  @click="
                    state.behavior === 'add' &&
                      onCardSubTypeChange({ model, field, value: o.value })
                  "
                >
                  <div class="label">{{ o.label }}</div>
                  <div class="desc">{{ o.desc }}</div>
                </div>
              </div>
            </template>

            <!-- 有效期 -->
            <template #validDate="{ model, field }">
              <a-input-number v-model:value="model[field]" :min="0" :max="9999999" :precision="0">
                <template #addonAfter>
                  <a-select
                    v-model:value="model.validDateUnit"
                    placeholder="单位"
                    style="width: 80px"
                    default-value="年"
                  >
                    <a-select-option
                      v-for="item in proValidDateUnit"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </template>
              </a-input-number>
            </template>
          </BasicForm>
        </div>

        <div v-show="state.cateType === 'S'" class="card">
          <a-row :gutter="8" style="margin: 0 6px 12px 0">
            <a-col :span="12" class="c-title">产品消耗</a-col>
            <a-col :span="12" style="text-align: right">
              <a-button @click="onAddConsume" :icon="h(PlusCircleOutlined)" size="small"
                >添加配料
              </a-button>
            </a-col>
          </a-row>

          <BasicTable
            @register="state.S.registerTable"
            :dataSource="state.S.dataSource"
            :scroll="{ y: 320 }"
          >
            <template #action="{ record }">
              <TableAction
                :divider="true"
                :actions="[
                  {
                    color: 'success',
                    label: '删除',
                    popConfirm: {
                      title: '您确定要删除吗',
                      confirm: () => onDeleteConsume(record),
                    },
                  },
                ]"
              />
            </template>
          </BasicTable>
        </div>

        <div v-show="exist(state.cardSubType, ['201', '202', '203'])" class="card">
          <a-row :gutter="8" style="margin: 0 6px 12px 0">
            <a-col :span="12" class="c-title">购卡权益</a-col>
            <a-col :span="12" style="text-align: right">
              <a-button @click="onAddCardGoods" :icon="h(PlusCircleOutlined)" size="small"
                >添加服务
              </a-button>
            </a-col>
          </a-row>

          <BasicTable
            @register="state.C.G.registerTable"
            :dataSource="state.C.G.dataSource"
            :scroll="{ y: 320 }"
          >
            <template #action="{ record }">
              <TableAction
                :divider="true"
                :actions="[
                  {
                    color: 'success',
                    label: '删除',
                    popConfirm: {
                      title: '您确定要删除吗',
                      confirm: () => onDeleteCardGoods(record),
                    },
                  },
                ]"
              />
            </template>
          </BasicTable>
        </div>

        <div v-show="state.cateType === 'C'" class="card">
          <a-row :gutter="8" style="margin: 0 6px 12px 0">
            <a-col :span="12" class="c-title">赠送权益</a-col>
            <a-col :span="12" style="text-align: right">
              <a-button @click="onAddCardGive" :icon="h(PlusCircleOutlined)" size="small"
                >添加权益
              </a-button>
            </a-col>
          </a-row>

          <a-tabs v-model:activeKey="state.C.cateType" type="line">
            <a-tab-pane v-for="o in proCategoryType2" :key="o.value" :tab="o.label">
              <BasicTable
                @register="state.C[o.value].registerTable"
                :dataSource="state.C[o.value].dataSource"
                :scroll="{ y: 320 }"
              >
                <template #action="{ record }">
                  <TableAction
                    :divider="true"
                    :actions="[
                      {
                        color: 'success',
                        label: '删除',
                        popConfirm: {
                          title: '您确定要删除吗',
                          confirm: () => onDeleteCardGive(record, o.value),
                        },
                      },
                    ]"
                  />
                </template>
              </BasicTable>
            </a-tab-pane>
          </a-tabs>
        </div>

        <div v-show="!!state.cateType" class="card">
          <div class="c-title"> 其他信息</div>

          <BasicForm @register="registerForm2" class="form">
            <template #image="{ field }">
              <div @mousemove.stop="state.imgType = 'image/png,image/jpeg'">
                <Attachment
                  :accept="state.imgType"
                  list-type="picture-card"
                  :multiple="false"
                  :maxCount="1"
                  :disabled="false"
                  v-model:data-source="state.form[field]"
                />
              </div>
            </template>

            <template #video="{ field }">
              <div @mousemove.stop="state.imgType = 'audio/mp4,video/mp4,video/mpeg'">
                <Attachment
                  :accept="state.imgType"
                  list-type="text"
                  :multiple="false"
                  :maxCount="1"
                  :disabled="false"
                  title="上传视频"
                  v-model:data-source="state.form[field]"
                />
              </div>
            </template>
          </BasicForm>
        </div>
      </div>
    </Content>

    <Footer class="fixed bottom-0">
      <a-flex align="center" justify="center" gap="middle" class="f-body">
        <a-button @click="router.back()"> 取消</a-button>

        <!-- <a-button v-if="state.behavior === 'add'" danger @click="onSave(2)"> 保存并继续</a-button> -->

        <a-button type="primary" @click="onSave(1)">{{ '保存' }} </a-button>
      </a-flex>
    </Footer>

    <Category @register="registerCategory" @complete="cateParams.version = Math.random()" />
    <Unit @register="registerUnit" @complete="onUnitComplete" />
  </div>
</template>
<script setup>
  import { h, onActivated, onMounted, reactive, ref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { PlusCircleOutlined, SettingOutlined } from '@ant-design/icons-vue';
  import { BasicTable, TableAction, useTable } from '@/components/Table';

  import Attachment from '@/widget/attachment.vue';
  import {
    getChildren,
    getChildrenLabel,
    proCardType,
    proCategoryType2,
    proConsumeType,
    proStatus,
    proValidDateUnit,
    proValidType,
  } from '@/api/ds';
  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import Footer from '@/widget/footer.vue';

  import { useRoute, useRouter } from 'vue-router';
  import { GET, POST, POST_API, PUT } from '@/api/http';
  import {
    copy,
    exist,
    getAttachment,
    initFileAttachment,
    initImgAttachment,
    isNil,
    jointPath,
  } from '@/api/util';
  import { useMessage } from '@/hooks/web/useMessage';
  import { Button, InputNumber } from 'ant-design-vue';
  import { useDrawer } from '@/components/Drawer';

  import Category from '../category/detail.vue';
  import Unit from './unit.vue';
  import { useModal } from '@/components/Modal';
  import { getConvertUnitText, getUnitText } from './util.js';
  import { useScrollToError } from '@/hooks/web/useScrollToError';
  import { useRequest } from 'vue-request';

  const [registerCategory, { openDrawer: openCategory }] = useDrawer();
  const [registerUnit, { openModal: openUnit }] = useModal();

  const { createMessage } = useMessage();
  const { scrollIntoView } = useScrollToError();

  const route = useRoute(),
    router = useRouter();

  const recordRef = ref({});
  const { behavior } = route.meta;
  const { cateType: initCateType = behavior === 'add' ? 'P' : null, key = null } = route.query;

  const [registerTableS] = useTable({
    columns: [
      {
        title: '产品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
      },

      {
        title: '消耗',
        dataIndex: 'csmValue',
        ellipsis: false,
        width: 170,
        customRender: ({ value, record }) => {
          return h(InputNumber, {
            value,
            min: 0,
            max: 9999999,
            precision: 0,
            ['onUpdate:value']: (nVal) => {
              record.csmValue = nVal;
            },
          });
        },
      },

      {
        title: '单位',
        dataIndex: 'csmUnit',
        ellipsis: false,
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'left',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  const [registerTableCG] = useTable({
    columns: [
      {
        title: '服务名称',
        dataIndex: 'goodsName',
        ellipsis: false,
      },

      {
        title: '服务时长',
        dataIndex: 'duration',
        ellipsis: false,
        customRender: ({ value }) => `${value ?? 0}分钟`,
      },

      {
        title: '服务价格',
        dataIndex: 'salePrice',
        ellipsis: false,
        customRender: ({ value }) => `${value ?? 0}元`,
      },

      {
        title: '可用次数',
        dataIndex: 'qty',
        ellipsis: false,
        width: 170,
        customRender: ({ value, record }) => {
          return h(InputNumber, {
            addonAfter: '次',
            value,
            min: 0,
            max: 9999999,
            precision: 0,
            ['onUpdate:value']: (nVal) => {
              record.qty = nVal;
            },
          });
        },

        ifShow: () => state.cardSubType === '201',
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'left',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  const [registerTableCP] = useTable({
    columns: [
      {
        title: '产品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
      },

      {
        title: '规格',
        dataIndex: 'specs',
        ellipsis: false,
      },

      {
        title: '售卖价格',
        dataIndex: 'salePrice',
        ellipsis: false,
        customRender: ({ value }) => `${value ?? 0}元`,
      },

      {
        title: '赠送数量',
        dataIndex: 'qty',
        ellipsis: false,
        width: 170,
        customRender: ({ value, record }) => {
          return h(InputNumber, {
            addonAfter: record.saleUnit,
            value,
            min: 0,
            max: 9999999,
            precision: 0,
            ['onUpdate:value']: (nVal) => {
              record.qty = nVal;
            },
          });
        },
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'left',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  const [registerTableCS] = useTable({
    columns: [
      {
        title: '服务名称',
        dataIndex: 'goodsName',
        ellipsis: false,
      },

      {
        title: '服务时长',
        dataIndex: 'duration',
        ellipsis: false,
        customRender: ({ value }) => `${value ?? 0}分钟`,
      },

      {
        title: '服务价格',
        dataIndex: 'salePrice',
        ellipsis: false,
        customRender: ({ value }) => `${value ?? 0}元`,
      },

      {
        title: '赠送次数',
        dataIndex: 'qty',
        ellipsis: false,
        width: 170,
        customRender: ({ value, record }) => {
          return h(InputNumber, {
            addonAfter: '次',
            value,
            min: 0,
            max: 9999999,
            precision: 0,
            ['onUpdate:value']: (nVal) => {
              record.qty = nVal;
            },
          });
        },
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'left',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  const [registerTableCC] = useTable({
    columns: [
      {
        title: '卡项名称',
        dataIndex: 'cardName',
        ellipsis: false,
      },

      {
        title: '卡项类型',
        dataIndex: 'cardSubType',
        ellipsis: false,
        customRender: ({ record }) =>
          getChildrenLabel(proCardType, record.cardType, record.cardSubType),
      },

      {
        title: '卡项价格',
        dataIndex: 'salePrice',
        ellipsis: false,
        customRender: ({ value }) => `${value ?? 0}元`,
      },

      {
        title: '赠送次数',
        dataIndex: 'qty',
        ellipsis: false,
        width: 170,
        customRender: ({ value, record }) => {
          return h(InputNumber, {
            addonAfter: '次',
            value,
            min: 0,
            max: 9999999,
            precision: 0,
            ['onUpdate:value']: (nVal) => {
              record.qty = nVal;
            },
          });
        },
      },
    ],
    pagination: false,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
    actionColumn: {
      title: '操作',
      align: 'left',
      width: 90,
      dataIndex: 'action',
      fixed: 'right',
      slots: { customRender: 'action' },
    },
  });

  const state = reactive({
    behavior,
    cateType: initCateType,
    imgType: 'image/png, image/jpeg',
    cardType: null,
    cardSubType: null,

    form: {
      goodsImage: [],
      goodsVideo: [],
      cardImage: [],
      cardVideo: [],
      purUnit: null,
      saleUnit: null,
      csmUnit: null,
      purToSale: null,
      saleToCsm: null,
    },

    S: {
      registerTable: registerTableS,
      dataSource: [],
    },
    C: {
      G: {
        registerTable: registerTableCG,
        dataSource: [],
      },

      P: {
        registerTable: registerTableCP,
        dataSource: [],
      },
      S: {
        registerTable: registerTableCS,
        dataSource: [],
      },
      C: {
        registerTable: registerTableCC,
        dataSource: [],
      },
    },
  });

  const cateParams = ref({ cateSubName: null, cateType: 'P', version: null });

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 12, style: { paddingRight: '36px' } },

    schemas: getSchema1(),
    showActionButtonGroup: false,
  });

  const [registerForm2, form2] = useForm({
    labelWidth: 100,
    baseColProps: { span: 12, style: { paddingRight: '36px' } },

    schemas: getSchema2(),
    showActionButtonGroup: false,
  });

  const formList = [form1, form2];

  async function onCateTypeChange({ model, field, value: cateType }) {
    model[field] = cateType;

    state.cateType = cateType;

    cateParams.value.cateSubName = null;
    cateParams.value.cateType = cateType;

    if (cateType !== 'C') {
      state.cardType = null;
      state.cardSubType = null;
      form1.setFieldsValue({ cardType: null, cardSubType: null });
    } else if (state.behavior === 'add') {
      model.cardType = '200';
      state.cardType = '200';
      model.validDateUnit = '年';
    }

    model.thirdCateCode = null;
    await updateSchema();
  }

  async function onCardTypeChange({ value: cardType }) {
    state.cardType = cardType;
    let cardSubType = null;

    if (cardType === '100') {
      //金额卡
      cardSubType = getChildren(proCardType, cardType)?.[0]?.value ?? null;
    }

    state.cardSubType = cardSubType;
    await form1.setFieldsValue({ cardSubType });
    await updateSchema();

    const formValue = {
      cateType: state.cateType,
      cardType: cardType,
    };

    form1.resetFields();
    form1.setFieldsValue(formValue);
  }

  async function onCardSubTypeChange({ model, field, value: cardSubType }) {
    model[field] = cardSubType;

    state.cardSubType = cardSubType;
    await updateSchema();
  }

  async function updateSchema() {
    await form1.setProps({ schemas: getSchema1() });
    await form2.setProps({ schemas: getSchema2() });

    formList.forEach((f) => {
      try {
        f.clearValidate();
      } catch (e) {
        //
      }
    });
  }

  function getSchema1() {
    const { cateType, cardType, cardSubType } = state;
    const { source } = recordRef.value;

    const list = [
      {
        label: '商品类型',
        field: 'cateType',
        required: true,
        component: 'RadioGroup',
        slot: 'cateType',
        colProps: {
          span: 24,
        },
      },
    ];

    const salePrice = {
      label: '售卖价格',
      field: 'salePrice',
      required: true,
      component: 'InputNumber',
      componentProps: {
        min: 0,
        max: 9999999,
        precision: 2,
        addonAfter: '元',
      },
      itemProps: {
        wrapperCol: {
          span: 14,
        },
      },
    };

    const status = {
      label: '商品状态',
      field: 'status',
      required: true,
      component: 'RadioGroup',
      componentProps: {
        options: proStatus,
      },
    };

    if (cateType === 'P' || cateType === 'S') {
      list.push(
        ...[
          {
            label: cateType === 'S' ? '服务名称' : '产品名称',
            field: 'goodsName',
            required: true,
            component: 'Input',
            componentProps: {
              disabled: source === 1,
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
          {
            label: '产品分类',
            field: 'thirdCateCode',
            required: true,
            component: 'ApiSelect',
            suffix: () =>
              h(
                Button,
                { type: 'link', onClick: () => openCategory(true, { behavior: 'add' }) },
                '添加分类',
              ),
            componentProps: {
              valueField: 'cateCode',
              labelField: 'cateSubName',
              showSearch: true,
              filterOption: false,
              api: async (...args) => {
                const res = await POST_API('/product/libCategoryStoreListAll')(...args);
                run();
                return res;
              },
              params: cateParams,
              onSearch: (value) => {
                cateParams.value.cateSubName = value;
              },
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },

          salePrice,
          status,
        ],
      );
    }

    if (cateType === 'P') {
      list.push(
        ...[
          {
            label: '产品单位',
            field: 'sPurUnit',
            required: true,
            component: 'Input',

            componentProps: {
              // disabled: true,
              readonly: true,
              addonAfter: h(
                'div',
                {
                  className: 'use',
                  onClick: () => source !== 1 && openUnit(true, { record: state.form }),
                },
                [h(SettingOutlined)],
              ),
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
          {
            label: '换算单位',
            field: 'sSaleToCsm',
            required: true,
            component: 'Input',

            componentProps: {
              // disabled: true,
              readonly: true,
              addonAfter: h(
                'div',
                {
                  className: 'use',
                  onClick: () => source !== 1 && openUnit(true, { record: state.form }),
                },
                [h(SettingOutlined)],
              ),
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
          {
            label: '安全存量',
            field: 'safeStock',
            required: false,
            component: 'InputNumber',
            componentProps: {
              min: 0,
              max: 9999999,
              precision: 0,
              addonAfter: state.form.saleUnit || '',
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
          {
            label: '回购提醒',
            field: 'alertStock',
            required: false,
            component: 'InputNumber',
            componentProps: {
              min: 0,
              max: 9999999,
              precision: 0,
              addonAfter: '天',
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
        ],
      );
    } else if (cateType === 'S') {
      list.push(
        ...[
          {
            label: '服务时长',
            field: 'duration',
            required: true,
            component: 'InputNumber',
            componentProps: {
              min: 0,
              max: 9999999,
              precision: 0,
              addonAfter: '分钟',
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
          {
            label: '回访间隔',
            field: 'visitBack',
            required: false,
            component: 'InputNumber',
            componentProps: {
              min: 0,
              max: 9999999,
              precision: 0,
              addonAfter: '天',
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
          {
            label: '消费间隔提醒',
            field: 'csmInterval',
            required: false,
            component: 'InputNumber',
            componentProps: {
              min: 0,
              max: 9999999,
              precision: 0,
              addonAfter: '天',
            },
            itemProps: {
              wrapperCol: {
                span: 14,
              },
            },
          },
        ],
      );
    }

    if (cateType === 'C') {
      list.push({
        label: '卡项类型',
        field: 'cardType',
        required: true,
        component: 'RadioGroup',

        componentProps: {
          options: proCardType,
          disabled: source === 1 || state.behavior !== 'add',
          onChange: (e) => {
            if (e?.target) {
              onCardTypeChange({ value: e.target.value });
            }
          },
        },
        colProps: {
          span: 24,
        },
      });
    }

    if (cardType) {
      list.push({
        label: '次卡类型',
        field: 'cardSubType',
        required: cardType === '200',
        component: 'RadioGroup',
        slot: 'cardSubType',
        show: cardType === '200',
        colProps: {
          span: 24,
        },
      });
    }

    if (cardSubType) {
      const cardName = {
        label: '卡项名称',
        field: 'cardName',
        required: true,
        component: 'Input',
        componentProps: {
          disabled: source === 1,
        },
        itemProps: {
          wrapperCol: {
            span: 14,
          },
        },
      };

      const validType = {
        label: '有效期类型',
        field: 'validType',
        required: true,
        component: 'Select',

        componentProps: {
          options: proValidType,
          onChange: (value) => {
            if (value === '40' || value === '30') {
              form1.setFieldsValue({ validDate: null, validDateUnit: null });
            }

            if (value === '30') {
              updateSchema();
            } else {
              form1.setFieldsValue({ fixedExpire: null });
            }
          },
        },
        itemProps: {
          wrapperCol: {
            span: 14,
          },
        },
      };

      const fixedExpire = {
        label: '有效期',
        field: 'fixedExpire',
        component: 'DatePicker',
        componentProps: {
          valueFormat: 'YYYY-MM-DD',
          format: 'YYYY-MM-DD',
        },

        ifShow: ({ values }) => {
          const { validType } = values;
          return validType === '30';
        },
        dynamicRules: ({ values }) => {
          const { validType } = values;
          return [{ type: 'any', required: validType === '30' }];
        },
        itemProps: {
          wrapperCol: {
            span: 14,
          },
        },
      };

      const validDate = {
        label: '有效期',
        field: 'validDate',
        component: 'InputNumber',
        slot: 'validDate',
        ifShow: ({ values }) => {
          const { validType } = values;
          return validType !== '30' && validType !== '40';
        },
        dynamicRules: ({ values }) => {
          const { validType } = values;

          if (validType === '30' || validType === '40') {
            return [{ type: 'any', required: false }];
          }

          return [
            { type: 'any', required: true },
            {
              validator: () => {
                const { validDateUnit } = form1.getFieldsValue();
                if (!validDateUnit) {
                  return Promise.reject('请选择有效期单位');
                }

                return Promise.resolve();
              },
            },
          ];
        },
        itemProps: {
          wrapperCol: {
            span: 14,
          },
        },
      };

      const validDateUnit = {
        label: '有效期单位',
        field: 'validDateUnit',
        required: false,
        component: 'Input',
        show: false,
        itemProps: {
          wrapperCol: {
            span: 14,
          },
        },
      };

      if (cardSubType === '201' || cardSubType === '203') {
        list.push(
          ...[
            cardName,
            salePrice,
            {
              label: '总服务次数',
              field: 'oriPoint',
              component: 'InputNumber',
              componentProps: {
                min: 0,
                max: 9999999,
                precision: 0,
                addonAfter: '次',
              },

              rules: [
                {
                  type: 'any',
                  required: true,
                },
                {
                  validator: () => {
                    const { oriPoint } = form1.getFieldsValue();

                    if (cardSubType === '201') {
                      const qty =
                        state.C.G.dataSource?.reduce((pv, cv) => pv + (cv.qty || 0), 0) ?? 0;
                      console.log(qty);
                      if (parseInt(oriPoint) !== qty) {
                        return Promise.reject('总服务次数与购卡权益可用次数不一致');
                      }
                    }

                    return Promise.resolve();
                  },
                },
              ],
              itemProps: {
                wrapperCol: {
                  span: 14,
                },
              },
            },
            status,
            validType,
            validDate,
            validDateUnit,
            fixedExpire,
          ],
        );
      } else if (cardSubType === '202') {
        list.push(
          ...[cardName, salePrice, validType, validDate, validDateUnit, fixedExpire, status],
        );
      } else if (cardSubType === '101') {
        list.push(
          ...[
            cardName,
            salePrice,

            {
              label: '充值金额',
              field: 'oriPoint',
              required: true,
              component: 'InputNumber',
              componentProps: {
                min: 0,
                max: 9999999,
                precision: 2,
                addonAfter: '元',
              },
            },
            {
              label: '赠送金额',
              field: 'bounsScore',
              required: true,
              component: 'InputNumber',
              componentProps: {
                min: 0,
                max: 9999999,
                precision: 2,
                addonAfter: '元',
              },
            },
            {
              label: '居家产品折扣',
              field: 'discountProduct',
              required: true,
              component: 'InputNumber',
              componentProps: {
                min: 0,
                max: 100,
                precision: 0,
                addonAfter: '%',
              },
            },
            {
              label: '疗程服务折扣',
              field: 'discountService',
              required: true,
              component: 'InputNumber',
              componentProps: {
                min: 0,
                max: 100,
                precision: 0,
                addonAfter: '%',
              },
            },
            {
              label: '次卡折扣',
              field: 'discountTimes',
              required: true,
              component: 'InputNumber',
              componentProps: {
                min: 0,
                max: 100,
                precision: 0,
                addonAfter: '%',
              },
            },
            status,
            validType,
            validDate,
            validDateUnit,
            fixedExpire,
            {
              label: '卡耗方式',
              field: 'consumeType',
              required: true,
              component: 'RadioGroup',

              componentProps: {
                options: proConsumeType,
              },
            },
          ],
        );
      }
    }

    return list;
  }

  function getSchema2() {
    const { cateType } = state;

    if (!cateType) {
      return [];
    }

    const flag = cateType === 'P' || cateType === 'S';
    const imageField = flag ? 'goodsImage' : 'cardImage';
    const videoField = flag ? 'goodsVideo' : 'cardVideo';

    return [
      {
        label: '图片展示',
        field: imageField,
        required: false,
        component: 'Upload',
        slot: 'image',
      },
      {
        label: '视频展示',
        field: videoField,
        required: false,
        component: 'Upload',
        slot: 'video',
      },

      {
        label: '商品描述',
        field: 'sellPoint',
        required: false,
        component: 'InputTextArea',
        componentProps: {
          showCount: true,
          maxlength: 100,
        },
        colProps: {
          span: 24,
        },
      },
    ];
  }

  onActivated(() => {
    sessionStorage.removeItem('cardName');
  });

  const first = ref(true);

  async function init() {
    const { cateType } = state;
    const initData = { cateType, status: 1 };

    if (state.behavior === 'edit') {
      let record = null;

      if (cateType === 'P') {
        record = await GET('/product/productStoreDetail', { productId: key });
      } else if (cateType === 'S') {
        record = await GET('/product/serviceStoreDetail', { serviceId: key });
      } else if (cateType === 'C') {
        record = await POST('/card/getCardBatchInfoBean', { batchNo: key });

        const { cardType, cardSubType } = record || {};
        state.cardType = cardType;
        state.cardSubType = cardSubType;
      }

      record ||= {};

      recordRef.value = record;
      cateParams.value.cateType = cateType;

      await updateSchema();
    }

    //初始化表单
    Object.assign(initData, recordRef.value);
    Object.assign(
      state.form,
      initImgAttachment(
        recordRef.value,
        ['goodsImage', 'cardImage'],
        initFileAttachment(recordRef.value, ['goodsVideo', 'cardVideo']),
      ),
    );

    formList.forEach((f) => {
      f.setFieldsValue(initData);
    });

    //初始化单位
    const { purUnit, saleUnit, csmUnit, purToSale, saleToCsm } = recordRef.value;
    Object.assign(state.form, {
      purUnit,
      saleUnit,
      csmUnit,
      purToSale,
      saleToCsm,
    });

    window._consume_ = null;
    window._cardGoods_ = null;
    window._cardGive_ = null;

    if (cateType === 'P') {
      const sPurUnit = getUnitText(recordRef.value, { suffix: '单位' }),
        sSaleToCsm = getConvertUnitText(recordRef.value);
      form1.setFieldsValue({ sPurUnit, sSaleToCsm });
    } else if (cateType === 'S') {
      //疗程服务
      const { consumeList } = recordRef.value;

      //统一命名
      consumeList?.forEach((o) => {
        const { productGoodsName: goodsName, csmUnit: saleUnit } = o;
        Object.assign(o, { goodsName, saleUnit });
      });

      state.S.dataSource = consumeList;
    } else if (cateType === 'C') {
      //卡项-购卡权益
      const {
        apiResultCardBatchGoodsBeanList,
        apiResultStoreProductBeans,
        apiResultStoreServiceBeans,
        apiResultCardBatchInfoBeans,
      } = recordRef.value;

      //统一命名
      apiResultCardBatchGoodsBeanList?.forEach((o) => {
        const { servicesName: goodsName, servicePrice: salePrice } = o;
        Object.assign(o, { goodsName, salePrice });
      });

      apiResultStoreServiceBeans?.forEach((o) => {
        const { servicesName: goodsName, servicePrice: salePrice } = o;
        Object.assign(o, { goodsName, salePrice });
      });

      apiResultCardBatchInfoBeans?.forEach((o) => {
        const { cardName: goodsName, batchNo: goodsSn } = o;
        Object.assign(o, { goodsName, goodsSn });
      });

      state.C.G.dataSource = apiResultCardBatchGoodsBeanList || [];
      state.C.P.dataSource = apiResultStoreProductBeans || [];
      state.C.S.dataSource = apiResultStoreServiceBeans || [];
      state.C.C.dataSource = apiResultCardBatchInfoBeans || [];
    }

    await updateSchema();
  }

  const { run } = useRequest(init, {
    manual: true,
  });

  onMounted(async () => {
    if (state.behavior === 'add' || !(state.cateType === 'P' || state.cateType === 'S')) {
      run();
    }
  });

  onActivated(() => {
    if (first.value) {
      first.value = false;
      return;
    }

    const { cateType } = state;
    if (cateType === 'S') {
      let { _consume_ } = window;

      if (_consume_) {
        state.S.dataSource = _consume_.P;
        window._consume_ = null;
      }
    } else if (cateType === 'C') {
      let { _cardGoods_, _cardGive_ } = window;

      if (_cardGoods_) {
        state.C.G.dataSource = _cardGoods_.S;
        window._cardGoods_ = null;
      }

      if (_cardGive_) {
        const { P, S, C } = _cardGive_;
        state.C.P.dataSource = P || [];
        state.C.S.dataSource = S || [];
        state.C.C.dataSource = C || [];

        window._cardGive_ = null;
      }
    }
  });

  async function onSave(type) {
    await Promise.all(formList.map((f) => f.validate())).catch((e) => {
      scrollIntoView();
      return Promise.inject(e);
    });
    const formData = formList.reduce((prev, f) => Object.assign(prev, f.getFieldsValue()), {});

    //附件
    const { goodsImage, goodsVideo, cardImage, cardVideo } = state.form;
    formData.goodsImage = getAttachment(goodsImage)?.[0]?.url ?? null;
    formData.goodsVideo = getAttachment(goodsVideo)?.[0]?.url ?? null;
    formData.cardImage = getAttachment(cardImage)?.[0]?.url ?? null;
    formData.cardVideo = getAttachment(cardVideo)?.[0]?.url ?? null;

    const { cateType, cardType, cardSubType } = state;
    formData.cardSubType ||= cardSubType;

    if (cateType === 'S') {
      //疗程服务
      const { dataSource = [] } = state.S;
      const { goodsSn: serviceGoodsSn, goodsName: serviceGoodsName } = recordRef.value;

      for (const item of dataSource) {
        const { goodsSn, goodsName, saleUnit, csmValue } = item;

        if (isNil(csmValue)) {
          createMessage.error(`请输入“${goodsName}”消耗数量`);
          return;
        }

        item.serviceGoodsSn ||= serviceGoodsSn;
        item.serviceGoodsName ||= serviceGoodsName;
        item.productGoodsSn ||= goodsSn;
        item.productGoodsName ||= goodsName;
        item.csmUnit ||= saleUnit;
      }

      formData.consumeList = dataSource;
    }

    if (cardType === '200') {
      //次卡-购卡权益
      const { G } = state.C;

      if (cardSubType === '201') {
        //有限次卡
        for (const item of G.dataSource) {
          const { goodsName, qty } = item;

          if (isNil(qty)) {
            createMessage.error(`请输入“${goodsName}”可用次数`);
            return;
          }
        }
      } else {
        G.dataSource.forEach((o) => {
          o.qty = null;
        });
      }

      formData.paramCardBatchGoodsBeanList = G.dataSource;
    }

    if (cardSubType) {
      //次卡-子项
      const { C } = state;

      const list = [];
      for (const o of proCategoryType2) {
        const benefitsType = o.value;
        const { dataSource } = C[benefitsType];

        for (const item of dataSource) {
          const { goodsName, qty: benefitsQty } = item;

          if (isNil(benefitsQty)) {
            createMessage.error(
              `请输入"${o.label}"->“${goodsName}”赠送${benefitsType === 'P' ? '数量' : '次数'}`,
            );
            return;
          }

          const { goodsSn: benefitsSn } = item;
          Object.assign(item, { benefitsType, benefitsSn, benefitsQty });
          list.push(item);
        }
      }

      formData.paramCardBatchBenefitsBeanList = list;
    }

    //保存
    const data = { ...recordRef.value, ...formData };

    if (cateType === 'P') {
      const { purUnit, saleUnit, csmUnit, purToSale, saleToCsm } = state.form;
      Object.assign(data, { purUnit, saleUnit, csmUnit, purToSale, saleToCsm });
    }

    if (state.behavior === 'add') {
      data.source = 2;
      if (cateType === 'P') {
        await POST('/product/productStoreInsert', data);
      } else if (cateType === 'S') {
        await POST('/product/serviceStoreInsert', data);
      } else if (cateType === 'C') {
        await POST('/card/insertCardBatch', data);
      }
    } else {
      if (cateType === 'P') {
        await PUT('/product/productStoreUpdate', data);
      } else if (cateType === 'S') {
        await PUT('/product/serviceStoreUpdate', data);
      } else if (cateType === 'C') {
        await POST('/card/updateCardBatch', data);
      }
    }

    createMessage.success('商品信息已保存');

    if (type === 2) {
      await router.replace(jointPath(route.path, { t: Math.random() }));
    } else {
      await router.back();
    }
  }

  async function onUnitComplete(record) {
    Object.assign(state.form, record);

    const sPurUnit = getUnitText(record, { suffix: '单位' }),
      sSaleToCsm = getConvertUnitText(record);

    form1.setFieldsValue({ sPurUnit, sSaleToCsm });
    await updateSchema();
  }

  function onAddConsume() {
    const { dataSource } = state.S;
    window._consume_ = copy({ P: dataSource });
    // router.push('/product/list/edit/consume');
    router.push({
      path: '/product/list/edit/consume',
      query: { goodsName: form1.getFieldsValue().goodsName },
    });
  }

  function onDeleteConsume({ productGoodsSn }) {
    const { dataSource } = state.S;
    const index = dataSource.findIndex((o) => o.productGoodsSn === productGoodsSn);

    if (index > -1) {
      dataSource.splice(index, 1);
    }
  }

  function onAddCardGoods() {
    form1.clearValidate();
    const { dataSource } = state.C.G;
    window._cardGoods_ = copy({ S: dataSource });
    // router.push('/product/list/edit/card-goods');
    router.push({
      path: '/product/list/edit/card-goods',
      query: { cardName: form1.getFieldsValue().cardName, cardSubType: state.cardSubType },
    });
  }

  function onDeleteCardGoods({ goodsSn }) {
    const { dataSource } = state.C.G;
    const index = dataSource.findIndex((o) => o.goodsSn === goodsSn);

    if (index > -1) {
      dataSource.splice(index, 1);
    }
  }

  function onAddCardGive() {
    form1.clearValidate();
    const { P, S, C } = state.C;
    window._cardGive_ = copy({ P: P.dataSource, S: S.dataSource, C: C.dataSource });
    router.push({
      path: '/product/list/edit/card-give',
      query: { cardName: form1.getFieldsValue().cardName },
    });
  }

  function onDeleteCardGive({ goodsSn }, cateType) {
    const { dataSource } = state.C[cateType];
    const index = dataSource.findIndex((o) => o.goodsSn === goodsSn);

    if (index > -1) {
      dataSource.splice(index, 1);
    }
  }
</script>

<style lang="less" scoped>
  .card {
    margin: 8px 0 24px;
    padding: 16px;
    background-color: #fff;

    .c-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      column-gap: 8px;
      color: #091f3d;
      font-size: 14px;
      font-weight: 600;
    }

    .form {
      padding: 24px 12px 0 0;
    }

    .hint {
      color: #acb4bf;
      font-size: 10px;
      font-weight: 400;
    }

    .cate-type {
      display: flex;
      flex-flow: row wrap;
      align-items: center;
      cursor: pointer;
      gap: 8px 12px;

      .cell {
        padding: 4px 20px;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
      }

      .tacit {
        border: 1px solid #e0e5ec;
        color: #091f3d;
      }

      .active {
        border: 1px solid @primary-color;
        background-color: @primary-color;
        color: #fff;
      }
    }

    .card-sub-type {
      display: flex;
      position: relative;
      flex-flow: row wrap;
      align-items: center;
      cursor: pointer;
      gap: 8px 12px;

      .cell {
        padding: 4px 20px;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        text-align: center;
      }

      .tacit {
        border: 1px solid #e0e5ec;
        color: #091f3d;
      }

      .active {
        border: 1px solid @primary-color;
        background-color: @primary-color;
        color: #fff;

        .desc {
          color: #fff;
        }
      }
    }
  }
</style>
